﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Data.SqlClient;	// MSSQL Interface

namespace GE_Database_Manager
{
	public partial class Standardized_Form : Form
	{
		// Delegates
		public delegate void PassDatabase(object sender);
		public PassDatabase passDatabase;

		private SqlConnection connection;

		public Standardized_Form()
		{
			InitializeComponent();

			// Set the Authentication method to Integrated Security by default
			comboBox_Authentication.SelectedIndex = 0;
		}

		private void button_Connect_Click(object sender, EventArgs e)
		{
			label_Status.Text = "Connecting...";

			try
			{
				connection = new SqlConnection();		// SQL Connection

				// Connect to the given server
				if (comboBox_Authentication.SelectedIndex == 0)		// Integrated Security
				{
					connection.ConnectionString = String.Format("Server={0};Integrated Security=true", textBox_ServerName.Text);
				}
				else	// SQL Server Authentication
				{
					connection.ConnectionString = String.Format("Server={0};User ID={1};Password={2}",
						textBox_ServerName.Text, textBox_Username.Text, textBox_Password.Text);
				}

				// Get a list of databases/catalogs
				connection.Open();
				DataTable tbl_databases = connection.GetSchema("Databases");
				connection.Close();

				// Populate dropdown menus
				comboBox_Database.Items.Clear();

				foreach (DataRow row in tbl_databases.Rows)
				{
					comboBox_Database.Items.Add(row["database_name"].ToString());
				}

				// Precondition: Connection has been successful
				groupBox_SelectData.Enabled = true;
				button_Ok.Enabled = true;
				label_Status.Text = "Successfully connected to server";
			}
			catch (Exception ex)
			{
				// Alert user
				MessageBox.Show(String.Format("Unable to connect to server '{0}':\r\n{1}", textBox_ServerName.Text, ex.Message),
					"Connection Unsuccessful!", MessageBoxButtons.OK, MessageBoxIcon.Error);
				label_Status.Text = "Ready to connect";
			};
		}

		private void button_Cancel_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private void button_Ok_Click(object sender, EventArgs e)
		{
			if (passDatabase != null)
			{
				passDatabase(new Standardized(connection, textBox_ServerName.Text, comboBox_Database.Text));
				this.Close();
			}
		}

		private void comboBox_Authentication_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (comboBox_Authentication.SelectedIndex == 0)
			{
				textBox_Username.Enabled = false;
				textBox_Password.Enabled = false;
				label_Password.Enabled = false;
				label_Username.Enabled = false;
			}
			else
			{
				textBox_Username.Enabled = true;
				textBox_Password.Enabled = true;
				label_Password.Enabled = true;
				label_Username.Enabled = true;
			}
		}
	}
}
